package com.books4sale.admin.service;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.books4sale.admin.dto.Profile;
import com.books4sale.admin.dto.tools.Helper;
import com.books4sale.admin.dto.tools.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class SaveProfileInfo extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String shopAddress = req.getParameter(Helper.SHOP_ADDRESS);
		String shopCity = req.getParameter(Helper.SHOP_CITY);
		String shopName = req.getParameter(Helper.SHOP_NAME);
		String shopPhone = req.getParameter(Helper.SHOP_PHONE);
		System.out.println(req.getCharacterEncoding());
		System.out.println(shopCity);
		Profile userProfile;
		Helper helper = Helper.get();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		userProfile = helper.isUserProfileExists();

		if (null != userProfile) {
			userProfile.setShopName(shopName);
			userProfile.setShopCity(shopCity);
			userProfile.setShopAddress(shopAddress);
			// TODO: set shop phone

		} else {
			Key profileKuy = KeyFactory.createKey(
					Profile.class.getSimpleName(), helper.getCurrentUser()
							.getEmail());
			userProfile = new Profile(profileKuy, shopName, shopAddress, shopCity, shopPhone, "");
		}
		
		try {
			pm.makePersistent(userProfile);
		} finally {
			pm.close();
		}
		resp.sendRedirect("/admin/index.jsp");
	}
}
